"""
使用RSS和公开API获取热点数据的服务（优化版）
"""
import asyncio
import json
import logging
import hashlib
from datetime import datetime
from typing import Dict, Any, List, Optional
import aiohttp

logger = logging.getLogger(__name__)


class RSSHotService:
    """RSS热点服务 - 使用公开可用的API"""
    
    def __init__(self):
        self.session = None
        self.timeout = aiohttp.ClientTimeout(total=10)  # 10秒超时
        self.headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
        }
    
    async def __aenter__(self):
        self.session = aiohttp.ClientSession(timeout=self.timeout)
        return self
    
    async def __aexit__(self, *args):
        if self.session:
            await self.session.close()
    
    async def fetch_github_trending(self) -> List[Dict[str, Any]]:
        """获取GitHub趋势"""
        url = "https://api.github.com/search/repositories"
        params = {
            'q': 'stars:>1000',
            'sort': 'stars',
            'order': 'desc', 
            'per_page': 10
        }
        
        try:
            async with self.session.get(url, params=params, headers={'Accept': 'application/vnd.github.v3+json'}) as response:
                if response.status == 200:
                    data = await response.json()
                    hot_list = []
                    for idx, repo in enumerate(data.get('items', [])[:10], 1):
                        hot_item = {
                            'rank': idx,
                            'title': repo['full_name'],
                            'description': (repo.get('description') or '')[:200],
                            'url': repo['html_url'],
                            'stars': repo['stargazers_count'],
                            'language': repo.get('language', 'Unknown'),
                            'source': 'github'
                        }
                        hot_list.append(hot_item)
                    return hot_list
        except asyncio.TimeoutError:
            logger.warning("GitHub API超时")
        except Exception as e:
            logger.error(f"GitHub API错误: {e}")
        return []
    
    async def fetch_v2ex_hot(self) -> List[Dict[str, Any]]:
        """获取V2EX热门"""
        url = "https://www.v2ex.com/api/topics/hot.json"
        
        try:
            async with self.session.get(url) as response:
                if response.status == 200:
                    data = await response.json()
                    hot_list = []
                    for idx, topic in enumerate(data[:10], 1):
                        hot_item = {
                            'rank': idx,
                            'title': topic['title'],
                            'url': topic['url'],
                            'replies': topic.get('replies', 0),
                            'source': 'v2ex'
                        }
                        hot_list.append(hot_item)
                    return hot_list
        except asyncio.TimeoutError:
            logger.warning("V2EX API超时")
        except Exception as e:
            logger.error(f"V2EX API错误: {e}")
        return []
    
    async def fetch_juejin_hot(self) -> List[Dict[str, Any]]:
        """获取掘金热门"""
        url = "https://api.juejin.cn/recommend_api/v1/article/recommend_all_feed"
        payload = {
            "id_type": 2,
            "client_type": 2608,
            "sort_type": 200,
            "cursor": "0",
            "limit": 10
        }
        
        try:
            async with self.session.post(url, json=payload) as response:
                if response.status == 200:
                    data = await response.json()
                    hot_list = []
                    for idx, item in enumerate(data.get('data', [])[:10], 1):
                        article = item.get('item_info', {})
                        hot_item = {
                            'rank': idx,
                            'title': article.get('article_info', {}).get('title', ''),
                            'brief': article.get('article_info', {}).get('brief_content', '')[:100],
                            'view_count': article.get('article_info', {}).get('view_count', 0),
                            'source': 'juejin'
                        }
                        hot_list.append(hot_item)
                    return hot_list
        except asyncio.TimeoutError:
            logger.warning("掘金API超时")
        except Exception as e:
            logger.error(f"掘金API错误: {e}")
        return []
    
    async def fetch_all(self) -> Dict[str, List[Dict[str, Any]]]:
        """并发获取所有平台数据"""
        tasks = {
            'github': self.fetch_github_trending(),
            'v2ex': self.fetch_v2ex_hot(),
            'juejin': self.fetch_juejin_hot()
        }
        
        results = {}
        for name, task in tasks.items():
            try:
                results[name] = await task
                logger.info(f"{name}: 获取 {len(results[name])} 条数据")
            except Exception as e:
                logger.error(f"{name} 失败: {e}")
                results[name] = []
        
        return results


async def main():
    """测试"""
    logging.basicConfig(level=logging.INFO)
    
    async with RSSHotService() as service:
        results = await service.fetch_all()
        
        print("\n=== 热点数据获取结果 ===")
        total = 0
        for platform, items in results.items():
            print(f"\n{platform.upper()}: {len(items)} 条")
            total += len(items)
            for item in items[:3]:
                print(f"  [{item['rank']}] {item['title'][:60]}")
        
        print(f"\n总计: {total} 条热点数据")
        return total > 0


if __name__ == "__main__":
    result = asyncio.run(main())
    exit(0 if result else 1)